package com.application.fabric.users.config.encryptAl;

import org.springframework.stereotype.Repository;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

@Repository
public class PictureMain {
    private int width = 90;// 验证码图片的默认宽度
    private int height = 40;// 验证码图片的默认高度
    private int codeCount = 4;// 验证码字符个数
    private int lineCount = 20;// 干扰线数量
    private  String code = "";// 验证码
    private BufferedImage buffImg = null;// 验证码图片
    static char[] codeSequence = { 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'P', 'Q', 'R',
            'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', '1', '2', '3', '4', '5', '6', '7', '8', '9' };
    public  void createCode() {
        Random random = new Random();
        int fontWidth = width / codeCount;// 字体的宽度
        int fontHeight = height - 5;// 字体的高度
        int codeX = 0;// 第一个字符的x轴坐标
        int codeY = height - 8;// 验证字符的y轴坐标
        // 定义图像buffer
        buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = buffImg.createGraphics();
        // 设置背景色
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, width, height);
        // 设置字体
        Font font = new Font("Fixedsys", Font.BOLD, fontHeight);
        g.setFont(font);

        // 设置干扰线
        for (int i = 0; i < lineCount; i++) {
            int xs = random.nextInt(width);
            int ys = random.nextInt(height);
            int xe = xs + random.nextInt(width);
            int ye = ys + random.nextInt(height);
            g.setColor(getRandColor(1, 255));
            g.drawLine(xs, ys, xe, ye);
        }

        // 画验证码
        for (int i = 0; i < codeCount; i++) {
            String strRand = String.valueOf(codeSequence[random.nextInt(codeSequence.length)]);
            g.setColor(new Color(20 + random.nextInt(110), 20 + random.nextInt(110), 20 + random.nextInt(110)));
            g.drawString(strRand, (i) * fontWidth - 2, codeY);
            code += strRand;
        }
    }

    // 得到随机颜色
    private Color getRandColor(int fc, int bc) {
        Random random = new Random();
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + random.nextInt(bc - fc);
        int g = fc + random.nextInt(bc - fc);
        int b = fc;
        Color c =new Color(r,g,b);
        return c;

    }

    public BufferedImage getmsg(){
        this.createCode();
        return buffImg;
    }
    public String getcode(){
        return code;
    }

    public void setcode(){
        code = "";
    }
}
